/**
 * dependencies
 */
var debug = require("debug")("cloudbox:wechat"),
    crypto = require("crypto");
var wechat = require('wechat');
var models = require("../models"),
    Token = models.Token,
    Order = models.Order,
    User = models.User;
var util_wechat = require("../utils/wechatutil");
var BufferHelper = require('bufferhelper');
var xml2js = require('xml2js');

// 支付请求类型 JS API网页支付
// JS API支付授权目录 http://117.78.6.144/wcpay/
// JS API支付请求实例 http://117.78.6.144/wcpay/req_payment
// 共享收货地址 是
// 维权通知URL http://117.78.6.144/wcpay/notification/rights
// 告警通知URL http://117.78.6.144/wcpay/notification/warn

/* GET wechat page. */
module.exports = function(app) {
    //告警接口
    app.post("/wcpay/notification/warn", function(req, res) {
        res.end("success");
    });
    //发货通知
    app.post("/wcpay/notification/notify", function(req, res) {
        new util_wechat().getAPI(function(api) {
            //获取订单postdata
            var buf = new BufferHelper();
            buf.load(req, function(err, buf) {
                if (err) {
                    debug("req body:", req.body);
                } else {
                    var xml = buf.toString('utf-8');
                    xml2js.parseString(xml, {
                        trim: true
                    }, function(e, r) {
                        debug("xml2js openid is", r.xml.OpenId.toString());
                        var openid = r.xml.OpenId.toString();
                        var pkg = getPaySign(req.query, r.xml.OpenId.toString());
                        api.deliverNotify(pkg, function(err, result) {
                            //订单更新，修改订单状态并更新订单下单人
                            debug("deliverNotify:", result);
                            var orderDao = new Order();
                            orderDao.updateOrderOpneIdByTradeno(req.query.out_trade_no, openid, function(err, numberaffected) {
                                if (err) {
                                    debug("updateOrderOpneIdByTradeno fail", err);
                                } else {
                                    //更新用户咨询次数
                                    orderDao.findOrderByTradeno(req.query.out_trade_no, function(err, order) {
                                        if (order.servicecount) {
                                            new User().updateUserCountByOpneIdBuy(openid, order.servicecount, function(err) {
                                                if (err) debug("updateUserCountByOpneIdBuy fail", err);
                                            })
                                        } else {
                                            debug("buy the services fail");
                                        }
                                    })
                                    debug("updateOrderOpneIdByTradeno success");
                                }
                            })
                            res.end("success"); //通知发货
                        });
                    });
                }
            });
        });
    });
    //维权接口
    app.post("/wcpay/notification/rights", function(req, res) {
        debug("this is rights:" + JSON.stringify(req.body));
        res.end("success");
    });
}

function getPaySign(querystr, openId) {
    var wechat = new util_wechat();
    var payinfo = {
        "appid": "wx631f54c7933d782f",
        "appkey": "EbPSkAN5HQsCZafaBFZdvYZNftosVV3Vxmnwl6x95PlWNexAkttzqyl0fKODZtdm819xmd4m1kARXUu9EaJI59ek5tWSq7FfNYrrZitJYOy1GQq7CgptRSAaimxyJaTB", //支付专用签名串，开通微信支付后微信通知邮件中找到
        "openid": openId,
        "transid": querystr.transaction_id,
        "out_trade_no": querystr.out_trade_no,
        "deliver_timestamp": String(Math.floor((new Date().getTime() / 1000))),
        "deliver_status": "1",
        "deliver_msg": "ok"
    };
    //paysign string
    var newpayinfo = wechat.sort(payinfo);
    var newpayinfo_str = wechat.json2string(newpayinfo);
    debug("payinfo str:" + newpayinfo_str);
    //get the payinfo sha1
    var sha1_newpayinfo_str = wechat.sha1(newpayinfo_str);
    debug("payinfo sha1:" + sha1_newpayinfo_str);

    //add sha1 to the payinfo
    newpayinfo["sign_method"] = "sha1";
    newpayinfo["app_signature"] = sha1_newpayinfo_str;
    delete newpayinfo["appkey"];
    debug("add sign payinfo:", newpayinfo);
    return newpayinfo;
}